//
//  AppWebViewController.swift
//  app
//
//  Created by gy on 2023/7/19.
//

import UIKit
import WebKit

class AppWebViewController: BaseViewController {

    private var webView: WKWebView!
    private var urlString: String?
    private var hud : MBProgressHUD?
    private var isPush = false
    
    // MARK: Lifecycle
    
    init(url: String?,isShowNav: Bool = false,isPush: Bool = false, isShowCloseBtn: Bool = false) {
        super.init()
        hidesBottomBarWhenPushed = true
        self.urlString = url
        navIsHidden = !isShowNav
        self.isPush = isPush
        backBtn.isHidden = !isShowCloseBtn
    }
        
    override func loadView() {
        configUI()
        loadUrl()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
                
        // 标题检测
        addTitleObserver()
    }
        
    // MARK: - loadUrl
    private func loadUrl() {
        if let urlString = urlString, let url = URL.encodedURL(string: urlString) {
            webView.load(URLRequest.init(url: url))
        }
    }
    func reloadUrl(_ urlString: String?) {
        self.urlString = urlString
        
        if let urlString = urlString, let url = URL.encodedURL(string: urlString) {
            webView.load(URLRequest.init(url: url))
        }
    }

    // MARK: - UIButtonAction
    @objc private func back() {
        
        if webView.canGoBack {
            webView.goBack()
        } else {
            backAction()
        }
        
    }
    
    // MARK: - configUI
    func configUI() {
        
        view = UIView()
            
        let config = WKWebViewConfiguration()
        config.allowsInlineMediaPlayback = true
        webView = WKWebView.init(frame: .zero, configuration: config)
        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.scrollView.delegate = self
        webView.scrollView.isUserInteractionEnabled = true
        view.addSubview(webView)
        view.addSubview(backBtn)
        
        // 约束
        webView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(view)
            make.top.equalTo(0)
        }
        backBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(Size.navigationBarWithoutStatusHeight)
            make.width.equalTo(38)
            make.height.equalTo(44)
        }
        
        backBtn.addTarget(self, action: #selector(back), for: .touchUpInside)
        
    }

    private lazy var backBtn: AppCustomButton = {
        let backBtn = AppCustomButton()
        backBtn.setImage(UIImage(named: "back_pop_black"), for: .normal) // self.presentingViewController == nil ? "navBack":"close_x")
        backBtn.isHidden = true
        return backBtn
    }()
   
    deinit {
        guard let webView = webView else { return }
        webView.removeObserver(self, forKeyPath: "title")
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
}

// MARK: - title变化监测
extension AppWebViewController {
    
    /// 监听WKWebView的title属性变化
    func addTitleObserver() {
        webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
    }
    
    // 监听标题变化的观察方法
    override func observeValue(forKeyPath keyPath: String?,
                               of object: Any?,
                               change: [NSKeyValueChangeKey : Any]?,
                               context: UnsafeMutableRawPointer?) {
        if keyPath == "title",
           let newTitle = change?[.newKey] as? String {
            // 更新iOS应用程序中的标题
            self.navigationItem.title = newTitle
//            MYLog("title 改变了",newTitle)
        }
    }
    
}

extension AppWebViewController : WKNavigationDelegate,WKUIDelegate,UIScrollViewDelegate {
    
    //页面开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
    }
    //开始返回内容
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        
    }
    //页面加载失败
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        hud?.label.text = "加载失败"
        hud?.hide(animated: true, afterDelay: 2)
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        MYLog("加载完成")
        
        self.title = webView.title
        hud?.hide(animated: true)
        
    }
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        guard let finalURL = navigationAction.request.url else {
            return decisionHandler(.cancel)
        }
        decisionHandler(.allow)
    }


}


